import {Component, OnInit} from '@angular/core';
import {User} from '../model/user-model';
import {AuthUserService} from '../auth-user.service';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
import {GuidUtil} from '../../utils/guid.util';

@Component({
    selector: 'app-auth-registration',
    templateUrl: './auth-registration.component.html',
    styleUrls: ['./auth-registration.component.css']
})
export class AuthRegistrationComponent implements OnInit {

    private user: User = new User();
    public formGroup: FormGroup;
    public success = false;

    public formErrors = {
        'username': '',
        'password': '',
        'confirmPassword': '',
    };
    validationMessages = {
        'username': {
            'required': 'Username is required',
            'minlength': 'The size for username should be between 4 and 32'
        },
        'password': {
            'required': 'Password is required',
        },
        'confirmPassword': {
            'required': 'Confirm Password is required',
        }
    };

    constructor(private authUserService: AuthUserService,
                private formBuilder: FormBuilder) {
    }

    ngOnInit() {

        this.formGroup = this.formBuilder.group({
            'username': [
                this.user.username,
                [
                    Validators.required,
                    Validators.minLength(4),
                    Validators.maxLength(32)
                ]
            ],
            'password': [
                this.user.password,
                [
                    Validators.required
                ]
            ],
            'confirmPassword': [
                this.user.confirmPassword,
                [
                    Validators.required
                ]
            ],
        });

        this.formGroup.valueChanges
            .subscribe(data => this.onValueChanged(data));
        this.onValueChanged();
    }

    onValueChanged(data?: any) {
        console.log(data);
        if (!this.formGroup) {
            return;
        }
        const form = this.formGroup;
        for (const field in this.formErrors) {
            this.formErrors[field] = '';
            const control = form.get(field);
            if (control && control.dirty && !control.valid) {
                const messages = this.validationMessages[field];
                for (const key in control.errors) {
                    this.formErrors[field] += messages[key] + ' ';
                }
            }
        }
    }

    doRegister() {
        this.user = this.formGroup.value;
        this.authUserService.save(this.user);
        this.success = true;
        this.formGroup.reset();
    }
}
